import XLSX from "xlsx-js-style";
import { mergeTableData } from "../../../tools/common-excel";
import { formatTabletoExcel } from "../../../tools/common-excel";
import { message, Modal } from "antd";
import { createCellPos } from "../Tools/index";
/**
 * [
 *   [a,b,c]
 * ]
 * to ->
 * [
 *    [{t: "n", v: 3, f: "A1+A2"}]
 * ]
 *
 * sourceData  带有公式的
 * gridData 展示的
 * metaCells 列类型，以及配置
 * @param name 导出excel名称
 * @param headerDescDatas 表格附加数据
 * @param refs
 * @param exporType 导出表格类型 default：细线  primiay:表格四周空白
 * @param isSign  是否有签字表
 * @constructor
 */
export const ExportToExcel = async function (name, headerDescDatas, //表格附加数据
refs, exportType, isSign) {
    const self = refs ? refs : this;
    const gridRef = self.gridRef ? self.gridRef : self;
    const isShowMaps = gridRef.isShowMaps;
    if (!isShowMaps) {
        gridRef.setRowColumnsMap();
    }
    const { datas, excelData, mergeArray, excel_columns, excel_rows, excel_columns_tablecfg, rows, } = formatTabletoExcel({
        self,
        headerDescDatas,
        exportType,
        isEditFormula: true,
        isSign,
    });
    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.aoa_to_sheet([...datas]);
    const worksheet2 = XLSX.utils.aoa_to_sheet([[], [...rows]]);
    worksheet["!merges"] = [...mergeArray];
    worksheet["!cols"] = [...excel_columns]; // 设置每个列的列宽，并且可以做隐藏列
    worksheet["!rows"] = [...excel_rows]; // 设置行高。
    worksheet2["!cols"] = [...excel_columns_tablecfg]; //  工作表
    worksheet2["!hidden"] = true;
    console.log(datas, "datas 数据");
    console.log(worksheet, "worksheet最终数据");
    XLSX.utils.book_append_sheet(workbook, worksheet, `${name}`);
    XLSX.utils.book_append_sheet(workbook, worksheet2, "TableConfig");
    XLSX.utils.book_set_sheet_visibility(workbook, 1, 1);
    console.log(workbook.SheetNames, "SheetNames");
    //spliceStrConfig(saveObj, worksheet);
    // await XLSX.writeFile(workbook, `${name}.xlsx`, {
    //   compression: true,
    // });
    if (!isShowMaps) {
        gridRef.setRowColumnsMap();
    }
    const dialog_result = await window["electronComponents"].showSaveDialog("xlsx", `${name}.xlsx`);
    if (window["businessService"] && !dialog_result.canceled) {
        const res = await window["businessService"].updateExcelAddFont({
            filePath: dialog_result.filePath,
            workbook,
        });
        if (res && +res.code === 200) {
            return message.success("导出成功");
        }
    }
    return {
        excelData,
        mergeArray,
    };
};
function spliceStrConfig(saveObj, worksheet) {
    const strConfig = JSON.stringify(saveObj);
    const splice_str = group(strConfig, 3000);
    XLSX.utils.sheet_add_aoa(worksheet, [
        [
            {
                w: splice_str.length,
                v: "",
            },
        ],
    ], {
        origin: "A200",
    });
    let origin = 1;
    for (let i = 0; i < splice_str.length; i++) {
        const splice = splice_str[i];
        const count_origin = origin + i;
        XLSX.utils.sheet_add_aoa(worksheet, [
            [
                {
                    w: splice,
                    v: "",
                },
            ],
        ], {
            origin: createCellPos(count_origin) + "200",
        });
    }
}
function group(string, step) {
    let r = [];
    for (let i = 0, len = string.length; i < len; i += step) {
        r.push(string.substr(i, i + step));
    }
    return r;
}
/**
 * 等待需求逻辑, 将格式数据存到数据库中. 存到excel的单元格中会被不同版本的excel进行数据处理.
 * 通过文件的后缀标识进行区分？
 * 或者单元格中存储一个格式存储的编号去数据库中取.
 * @param file
 * @constructor
 */
export const ImportExcel = function (file, refs) {
    const reader = new FileReader();
    const self = refs ? refs : this;
    reader.onload = (e) => {
        const data = e.target.result;
        /* reader.readAsArrayBuffer(file) -> data will be an ArrayBuffer */
        const workbook = XLSX.read(data);
        const sheetName = workbook.SheetNames[0];
        const sheetTableName = workbook.SheetNames[1];
        const sheet = workbook.Sheets[sheetName];
        const sheet_json = workbook.Sheets[sheetTableName]; //此数据为json配置数据
        let currentSheetjson = XLSX.utils.sheet_to_json(sheet, {
            header: 1,
            raw: false,
            blankrows: false,
        });
        // 获取sheet表2的table配置数据
        let sheetJsonData = sheet_json
            ? XLSX.utils.sheet_to_json(sheet_json, {
                header: 1,
                raw: false,
            })[0]
            : [];
        let tableStr = "";
        for (let i = 0; i < sheetJsonData.length; i++) {
            tableStr += sheetJsonData[i];
        }
        console.log(tableStr, "tableStr test");
        const tableConfig = tableStr ? JSON.parse(tableStr) : {};
        const { headerNewData, newData, titleData } = mergeTableData(tableConfig, currentSheetjson, refs);
        tableConfig.header = headerNewData;
        tableConfig.data = newData;
        const gridRef = self.handsonTableFs
            ? self.handsonTableFs.current
            : self.gridRef;
        //每次导入视为新表,转换新的id
        const newTableConfig = gridRef.gridService.resetCpasTableId(tableConfig); //重置tableId
        //导入了标题的模版才需要更新标题，默认不需要
        if (refs) {
            gridRef.props.fsTableRef.updateTableDescData(titleData); //更新fs类型table title数据
        }
        console.log("导入数据 tableConfig", tableConfig, JSON.stringify(tableConfig), "测试table数据");
        //加载新的表格数据
        gridRef.reloadTable(newTableConfig);
        /* DO SOMETHING WITH workbook HERE */
    };
    reader.readAsArrayBuffer(file);
};
/**追加到底稿平台 */
export const ExportToDraft = function (params) {
    const { draftPopupRef, draftSheetName } = params;
    const gridRef = this.gridRef ? this.gridRef : this;
    const isShowMaps = gridRef.isShowMaps;
    if (!isShowMaps) {
        gridRef.setRowColumnsMap();
    }
    const sheetData = formatTabletoExcel({ self: this });
    //处理完sheet数据再关闭行列关系开关,确保页面展示正常
    if (!isShowMaps) {
        gridRef.setRowColumnsMap();
    }
    draftPopupRef.current.show({
        title: "设置",
        okCallback: async (r, v) => {
            // 获取选中的数据
            console.log(r, "rrrr", "draftFilePath---draftSheetName", draftSheetName);
            try {
                // const { code, data } = await window.parent[
                const res = await window["businessService"].excelManageGetExcelData({
                    filePath: r,
                    sheetData,
                    sheetName: draftSheetName,
                });
                console.log(res, "res-------");
                if (res && +res?.code === 200) {
                    //message.success("操作成功");
                    console.log(res, "res---");
                    if (res?.status === "已完成" && res?.filePath) {
                        return Modal.confirm({
                            content: "已成功追加到底稿中",
                            cancelText: "取消",
                            okText: "点击查看",
                            onOk: async () => {
                                if (res?.filePath) {
                                    let electronComponents;
                                    if (window.parent) {
                                        electronComponents = window.parent["electronComponents"];
                                    }
                                    else {
                                        electronComponents = window["electronComponents"];
                                    }
                                    await electronComponents["openDialogToPath"](res.filePath);
                                }
                            },
                        });
                    }
                    else {
                        return message.success("操作成功");
                    }
                }
                else {
                    message.error("操作失败，请重试");
                }
            }
            catch (err) {
                message.success("操作失败，请重试");
                throw err;
            }
        },
    });
};
